package com.zxw.auth.security;


import com.zxw.auth.feign.UserOpenfeignApiService;
import com.zxw.common.api.ApiResult;
import com.zxw.common.entity.user.UserVO;
import com.zxw.common.enums.ResultCode;
import com.zxw.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @author admin
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private UserOpenfeignApiService userOpenfeignApiService;

    @Override
    public UserDetails loadUserByUsername(String username) {
        //根据用户名查询用户信息
        ApiResult<UserVO> apiResult = this.userOpenfeignApiService.queryByUsername(username);
        if (apiResult.getCode() != ResultCode.SUCCESS.getCode()) {
            throw new BizException(apiResult.getMessage(), apiResult.getCode());
        }
        UserVO userVO = apiResult.getData();

        if (Objects.isNull(userVO)) {
            throw new BizException(ResultCode.LOGIN_USER_NAME_NOT_FOUND);
//            throw new UsernameNotFoundException("用户名不存在");
        }

        if (!userVO.getEnabled()) {
//            throw new BizException(ResultCode.DISABLED_EXCEPTION);
            throw new DisabledException("账户被禁用");
        }

        //身份令牌
        // String principal = JSON.toJSONString(userVO);
        // return User.withUsername(principal).password(userVO.getPassword()).authorities(Collections.emptyList()).build();
        return new CustomerUserDetails(userVO);
    }
}
